﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace System.Windows.Media
{
	public static class ExtensionMethods
	{
		public static Color FromInt(this Color c, int argb)
		{
			c.A = (byte)((argb & -16777216) >> 0x18);
			c.R = (byte)((argb & 0xff0000) >> 0x10);
			c.G = (byte)((argb & 0xff00) >> 8);
			c.B = (byte)(argb & 0xff);
			return c;
		}

		public static Color FromHSV(this Color c, double Hue, double Saturation, double Value)
		{
			int h = (int)(Hue / 60);
			double f = Hue / 60 - h;
			double p = Value * (1 - Saturation);
			double q = Value * (1 - Saturation * f);
			double t = Value * (1 - Saturation * (1 - f));
			double[] rgb = null;
			if (h == 0 || h == 6)
			{
				rgb = new double[] { Value, t, p };
			}
			else if (h == 1)
			{
				rgb = new double[] { q, Value, p };
			}
			else if (h == 2)
			{
				rgb = new double[] { p, Value, t };
			}
			else if (h == 3)
			{
				rgb = new double[] { p, q, Value };
			}
			else if (h == 4)
			{
				rgb = new double[] { t, p, Value };
			}
			else if (h == 5)
			{
				rgb = new double[] { Value, p, q };
			}
			return Color.FromArgb(255, (byte)(255 * rgb[0]), (byte)(255 * rgb[1]), (byte)(255 * rgb[2]));
		}

		public static int ToInt(this Color c)
		{
			// Calc premultiplier once only. We need to use premultiplied ARGB32 
			// rather than convential ARGB.
			double alphaPreMultiplier = c.A / 255d;

			// Premultiply rgb values with alpha
			byte r = (byte)(c.R * alphaPreMultiplier);
			byte g = (byte)(c.G * alphaPreMultiplier);
			byte b = (byte)(c.B * alphaPreMultiplier);

			return (c.A << 24) | (r << 16) | (g << 8) | b;
		}

		public static Color Invert(this Color c)
		{
			Color r = new Color();
			r.A = c.A;
			r.R = (byte)(255 - c.R);
			r.G = (byte)(255 - c.G);
			r.B = (byte)(255 - c.B);
			return r;
		}
	}
}
